const mongoose = require('mongoose');

const transactionSchema = new mongoose.Schema({
    value: {
        type: Number,
        required: true
    },
    time: {
        type: Date,
        required: true
    }
});

const categorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    order: {
        type: Number,
        required: true,
        default: 0
    },
    icon: {
        type: String,
        required: true
    },
    id: {
        type: String,
        required: true,
        unique: true,
        index: true
    },
    type: {
        type: String,
        enum: ['expense', 'income'],
        required: true
    },
    data: {
        type: [transactionSchema],
        default: []
    }
}, {
    timestamps: true
});

// 添加预保存中间件，确保 id 字段存在
categorySchema.pre('validate', function(next) {
    console.log('预验证中间件 - 当前文档:', this.toObject());
    if (!this.id) {
        this.id = `${this.type}_${this.name.toLowerCase().replace(/\s+/g, '_')}`;
        console.log('预验证中间件 - 生成的ID:', this.id);
    }
    next();
});

// 添加保存前中间件，确保数据格式正确
categorySchema.pre('save', function(next) {
    console.log('预保存中间件 - 当前文档:', this.toObject());
    if (!this.id) {
        this.id = `${this.type}_${this.name.toLowerCase().replace(/\s+/g, '_')}`;
        console.log('预保存中间件 - 生成的ID:', this.id);
    }
    next();
});

module.exports = mongoose.model('Category', categorySchema); 